package com.mango9x.utils;

import java.util.ArrayList;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;


public class DatabaseAccessor {

	private DBHelper myDbHelper = null;
	private SQLiteDatabase rdb = null;
	private SQLiteDatabase wdb = null;
	private Context context;
	
	public DatabaseAccessor(Context context) {
		this.context = context;
	}
	
	public void open(){
		try {
			myDbHelper = new DBHelper(context);
			rdb = myDbHelper.getReadableDatabase();
			wdb = myDbHelper.getWritableDatabase();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	public void close(){
		try {
			myDbHelper.close();
			rdb.close();
			wdb.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public ArrayList<int[]> getFavoriteImages() {
		ArrayList<int[]> imageList = new ArrayList<int[]>();
		try {
			Cursor cur = rdb.rawQuery("SELECT "+DBHelper.CL_FILE_ID+","+DBHelper.CL_TIME+" FROM " + DBHelper.FAVORITES_TABLE +" ORDER BY "+DBHelper.CL_TIME+" DESC", null);
			while (cur.moveToNext()) {
				imageList.add(new int[]{cur.getInt(0),cur.getInt(1)});
			}
			cur.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return imageList;
	}
	public boolean isFavorite(int fileId) {
		boolean ret  =  false;
		try {
			Cursor cur = rdb.rawQuery("SELECT COUNT(*) FROM " + DBHelper.FAVORITES_TABLE +" WHERE "+DBHelper.CL_FILE_ID+" = " + fileId, null);
			if (cur.moveToNext()) {
				ret = (cur.getInt(0)>0);
			}
			cur.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ret;
	}
	public void addToFavorites(int fileId){
		try {
			ContentValues values = new ContentValues();
			values.put(DBHelper.CL_FILE_ID, fileId);
			values.put(DBHelper.CL_TIME, System.currentTimeMillis());
			wdb.insertOrThrow(DBHelper.FAVORITES_TABLE, null, values);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public void removeFromFavorites(int fileId){
		try {
			ContentValues values = new ContentValues();
			values.put(DBHelper.CL_FILE_ID, fileId);
			values.put(DBHelper.CL_TIME, System.currentTimeMillis());
			wdb.delete(DBHelper.FAVORITES_TABLE, " "+DBHelper.CL_FILE_ID +" = "+fileId +" " , null);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
